/// 基础模型接口
abstract class BaseModel {
  /// 转换为 JSON
  Map<String, dynamic> toJson();
}

/// Larapress 统一 HTTP 响应模型
class LarapressHttpModel {
  dynamic data;
  int? code;
  String? msg;

  LarapressHttpModel({this.data, this.code, this.msg});

  /// 从 JSON 创建实例
  factory LarapressHttpModel.fromJson(Map<String, dynamic> json) {
    return LarapressHttpModel(
      data: json['data'],
      code: json['code'] ?? json['status_code'] ?? 200,
      msg: json['msg'] ?? json['message'] ?? '请求成功',
    );
  }

  /// 转换为 JSON
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['data'] = this.data;
    data['code'] = code;
    data['msg'] = msg;
    return data;
  }

  /// 判断请求是否成功
  bool get isSuccess => code == 200 || code == 0;

  /// 获取错误信息
  String get errorMessage => msg ?? '未知错误';

  /// 获取数据（如果 data 是 JSON 字符串，则解析为 Map）
  Map<String, dynamic>? get dataAsMap {
    if (data == null) return null;
    try {
      return Map<String, dynamic>.from(data! as Map);
    } catch (e) {
      return null;
    }
  }

  /// 获取数据（如果 data 是 JSON 字符串，则解析为 List）
  List<dynamic>? get dataAsList {
    if (data == null) return null;
    try {
      return List<dynamic>.from(data! as List);
    } catch (e) {
      return null;
    }
  }

  @override
  String toString() {
    return 'LarapressHttpModel{data: $data, code: $code, msg: $msg}';
  }
}

/// 泛型响应模型 - 单个对象
class LarapressResponse<T extends BaseModel> {
  final T? data;
  final int? code;
  final String? msg;
  final bool isSuccess;

  LarapressResponse({this.data, this.code, this.msg, required this.isSuccess});

  /// 从 LarapressHttpModel 创建
  factory LarapressResponse.fromHttpModel(
    LarapressHttpModel httpModel,
    T Function(Map<String, dynamic>) fromJson,
  ) {
    T? parsedData;

    if (httpModel.data is Map<String, dynamic>) {
      try {
        parsedData = fromJson(httpModel.data as Map<String, dynamic>);
      } catch (e) {
        // 解析失败，data 为 null
      }
    }

    return LarapressResponse<T>(
      data: parsedData,
      code: httpModel.code,
      msg: httpModel.msg,
      isSuccess: httpModel.isSuccess,
    );
  }

  /// 获取错误信息
  String get errorMessage => msg ?? '未知错误';
}

/// 泛型响应模型 - 列表对象
class LarapressListResponse<T extends BaseModel> {
  final List<T>? data;
  final int? code;
  final String? msg;
  final bool isSuccess;

  LarapressListResponse({
    this.data,
    this.code,
    this.msg,
    required this.isSuccess,
  });

  /// 从 LarapressHttpModel 创建
  factory LarapressListResponse.fromHttpModel(
    LarapressHttpModel httpModel,
    T Function(Map<String, dynamic>) fromJson,
  ) {
    List<T>? parsedData;

    if (httpModel.data is List) {
      try {
        parsedData = (httpModel.data as List)
            .map((item) => fromJson(item as Map<String, dynamic>))
            .toList();
      } catch (e) {
        // 解析失败，data 为 null
      }
    }
    return LarapressListResponse<T>(
      data: parsedData,
      code: httpModel.code,
      msg: httpModel.msg,
      isSuccess: httpModel.isSuccess,
    );
  }

  /// 获取错误信息
  String get errorMessage => msg ?? '未知错误';
}

/// 分页信息模型
class PaginationModel {
  final int currentPage;
  final int limit;
  final int total;
  final int totalPages;
  final bool hasNextPage;
  final bool hasPrevPage;

  PaginationModel({
    required this.currentPage,
    required this.limit,
    required this.total,
    required this.totalPages,
    required this.hasNextPage,
    required this.hasPrevPage,
  });

  factory PaginationModel.fromJson(Map<String, dynamic> json) {
    return PaginationModel(
      currentPage: json['current_page'] ?? 1,
      limit: json['limit'] ?? 10,
      total: json['total'] ?? 0,
      totalPages: json['total_pages'] ?? 0,
      hasNextPage: json['has_next_page'] ?? false,
      hasPrevPage: json['has_prev_page'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'current_page': currentPage,
      'limit': limit,
      'total': total,
      'total_pages': totalPages,
      'has_next_page': hasNextPage,
      'has_prev_page': hasPrevPage,
    };
  }
}

/// 分页响应模型
class LarapressPaginatedResponse<T extends BaseModel> {
  final List<T>? data;
  final PaginationModel? pagination;
  final int? code;
  final String? msg;
  final bool isSuccess;

  LarapressPaginatedResponse({
    this.data,
    this.pagination,
    this.code,
    this.msg,
    required this.isSuccess,
  });

  /// 从 LarapressHttpModel 创建
  factory LarapressPaginatedResponse.fromHttpModel(
    LarapressHttpModel httpModel,
    T Function(Map<String, dynamic>) fromJson,
  ) {
    List<T>? parsedData;
    PaginationModel? pagination;

    if (httpModel.data is Map<String, dynamic>) {
      final dataMap = httpModel.data as Map<String, dynamic>;

      // 解析列表数据
      if (dataMap['list'] is List) {
        try {
          parsedData = (dataMap['list'] as List)
              .map((item) => fromJson(item as Map<String, dynamic>))
              .toList();
        } catch (e) {
          // 解析失败，data 为 null
        }
      }

      // 解析分页信息
      if (dataMap['pagination'] is Map<String, dynamic>) {
        try {
          pagination = PaginationModel.fromJson(
            dataMap['pagination'] as Map<String, dynamic>,
          );
        } catch (e) {
          // 解析失败，pagination 为 null
        }
      }
    }

    return LarapressPaginatedResponse<T>(
      data: parsedData,
      pagination: pagination,
      code: httpModel.code,
      msg: httpModel.msg,
      isSuccess: httpModel.isSuccess,
    );
  }

  /// 获取错误信息
  String get errorMessage => msg ?? '未知错误';
}
